package com.example.administrator.test;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import org.xutils.DbManager;
import org.xutils.db.table.DbModel;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/8/31.
 */

public class TwoFragment extends Fragment implements AdapterView.OnItemClickListener {

    GridView gridView;
    List<Book> list = new ArrayList<>();
    MyBookAdapter myBookAdapter;

    private MyApplication app1;
    DbManager db;

    View view;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_two,null);
        initView();
        gridView = (GridView)view.findViewById(R.id.tab2_book_grid);
        myBookAdapter = new MyBookAdapter(getActivity(),list);
        gridView.setAdapter(myBookAdapter);
        gridView.setOnItemClickListener(this);
        return view;
    }

    private void initView() {
        app1 = new MyApplication();
        db = x.getDb(app1.getDaoConfig());

        try {
            List<Book> find = db.selector(Book.class).findAll();
            if(find!=null&&find.size()!=0){
                list = find;
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent book_detail = new Intent(getActivity(),BookDetailActivity.class);
        Book book = list.get(i);
        book_detail.putExtra("book",book);
        startActivity(book_detail);
    }
}
